package com.icinfo.cloud.provider.punish.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.ApiVisitDataSourceEnum;
import com.icinfo.cloud.provider.punish.approval.vo.LineTerritoryInfoVo;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.dto.*;
import com.icinfo.cloud.provider.punish.service.ISimpleCaseService;
import com.icinfo.cloud.provider.punish.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.PoliceAdjudicationVo;
import com.icinfo.cloud.provider.punish.ucase.caseregister.dto.CaseHandlePersonInfoDto;
import com.icinfo.cloud.provider.punish.ucase.caseregister.vo.HandleAssistVo;
import com.icinfo.cloud.provider.punish.vo.*;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.web.BaseController;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 【掌上办案V1.1】  简易处罚前端控制器
 *
 * @Author zhengqiang
 * @Date 2022/6/14 14:22
 **/
@RestController
@RequestMapping("/app/simplecase")
@Slf4j
public class SimpleCaseController extends BaseController {

    @Resource
    private ISimpleCaseService simpleCaseService;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Value("${tzService.url}")
    private String url;

    /**
     * 描述: 简易案件保存方法
     *
     * @author: zhengqiang
     * @date: 2022/6/15
     * @param: saveDto
     * @return {@link Result< SimpleCaseSaveVo>}
     **/
    @PostMapping(value = "/saveCase")
    public Result<SimpleCaseSaveVo> saveCase(@RequestBody @Validated SimpleCaseSaveDto saveDto) {
        //判断是否案件移交了
        if (simpleCaseService.transferCaseToRecord(saveDto)) {
            //当简易程序需要移交时，不需要生成文书等逻辑，直接响应即可
            return Result.success("移交成功", null);
        }
        // 公安委托参数校验,并返回公安的裁量信息
        PoliceAdjudicationVo policeAdjudicationVo = simpleCaseService.checkSimpleCaseParameter(saveDto);
        // 简易程序罚款金额校验
        simpleCaseService.verifyDiscretionAmount(saveDto, policeAdjudicationVo);
        //去查一下当前缓存表中是否存在当前账号未完成的简易处罚案件缓存信息，如果有，获取数据来源和数据来源业务编码
        SimpleCaseQueryDto queryDto = new SimpleCaseQueryDto();
        SimpleCaseInfoVo simpleCaseInfoVo = simpleCaseService.getCaseRegisterDetailSimpleInfo(queryDto);
        if (!ObjectUtils.isEmpty(simpleCaseInfoVo)) {
            String dataSource = simpleCaseInfoVo.getDataSource();
            String dataSourceServiceId = simpleCaseInfoVo.getDataSourceServiceId();
            saveDto.setCaseSourceAppId(dataSource);
            saveDto.setDataSourceServiceId(dataSourceServiceId);
            saveDto.setCaseExternalActsCode(simpleCaseInfoVo.getCaseExternalActsCode());
            JSONObject json = new JSONObject();
            json.put("dataSource", dataSource);
            if(!ObjectUtils.isEmpty(dataSource) && !ApiVisitDataSourceEnum.TASKCENTER.getCode().equals(dataSource)){
                if(ApiVisitDataSourceEnum.ZJSXFJDZFXT_MOBILE.getId().equals(dataSource)){
                    saveDto.setCaseId(null);
                }
                saveDto.setExtraJsonInfo(json.toJSONString());

                List<CaseHandlePersonInfoDto> newHandlePersonList = saveDto.getHandlePersonInfoList();
                /*
                //替换掉原先的缓存的机构编码信息，使用当前登陆人的机构
                List<CaseHandlePersonInfoDto> handlePersonInfoList = simpleCaseInfoVo.getHandlePersonInfoList();
                newHandlePersonList.forEach(e->{
                    handlePersonInfoList.forEach(e1->{
                        if(e1.getHandlePersonType().equals(e.getHandlePersonType())){
                            *//*if(!ObjectUtil.isEmpty(e1.getHandleOrgCode()) && HandlePersonTypeEnum.MAIN.getCode().equals(e.getHandlePersonType())){
                                saveDto.setOrgCode(e1.getHandleOrgCode());
                            }*//*
                            e.setHandlePersonTel(e1.getHandlePersonTel());
                        }
                    });
                });*/
                saveDto.setHandlePersonInfoList(newHandlePersonList);
            }
        }
        //异常暂存数据处理
        simpleCaseService.dealTemporaryCaseData(saveDto);
        //保存简易处罚数据
        SimpleCaseSaveVo simpleCaseSaveVo = simpleCaseService.saveCase(saveDto);
        //不予处罚时，数据回流
        if (Constant.STRING_2.equals(saveDto.getInvestConclusion())) {
            simpleCaseService.callBackSimpleCaseInfo(saveDto.getCaseId());
        }
        if (ObjectUtil.isNotEmpty(simpleCaseSaveVo)) {
            //不是轻微违法或轻微违法予以处罚则生成处罚决定书
            if ( (ObjectUtils.isEmpty(saveDto.getIsSlightIllegal()) || Constant.STRING_2.equals(saveDto.getIsSlightIllegal()) )
                    || (Constant.STRING_1.equals(saveDto.getIsSlightIllegal()) && Constant.STRING_1.equals(saveDto.getInvestConclusion())) ) {

                //生成当场处罚决定书及现场照片证据的文书
                try {
                    simpleCaseService.dealSimpleCaseDocumentRecords(saveDto, null);
                    return Result.success(simpleCaseSaveVo);
                } catch (Exception e) {
                    log.error("立案失败！", e);
                    //生成文书异常,回滚案件保存数据
                     if (simpleCaseService.deleteCaseInfo(simpleCaseSaveVo.getCaseId())) {
//                        System.out.println("数据回滚成功!");
                         log.info("数据回滚成功！");
                    }
                    return Result.error("立案失败！" + e.getMessage());
                }
            } else {
                return Result.success(simpleCaseSaveVo);
            }

        }
        return Result.error("立案失败！");
    }

    /**
     * 描述： 查询简易案件录入数据
     *
     * @author: zhengqiang
     * @date: 2022/6/20
     * @param: queryDto
     * @return {@link Result< JSONObject>}
     **/
    @PostMapping(value = "/getCaseRegisterDetailSimpleInfo")
    public Result<SimpleCaseInfoVo> getCaseRegisterDetailSimpleInfo(@RequestBody SimpleCaseQueryDto queryDto) {
        SimpleCaseInfoVo simpleCaseInfoVo = simpleCaseService.getCaseRegisterDetailSimpleInfo(queryDto);
        return Result.success(simpleCaseInfoVo);
    }

    /**
     * 根据案由编码及当事人获取1年内重复违法次数
     *
     * @author: zhengqiang
     * @date: 2022/6/15
     * @param: queryDto
     * @return {@link Result}
     **/
    @PostMapping(value = "/getCaseMainCountByReasonCodeAndParty")
    public Result<Integer> getCaseMainCountByReasonCodeAndParty(@RequestBody CaseReasonQueryDto queryDto) {
        int count = simpleCaseService.getCaseMainCountByReasonCodeAndParty(queryDto);
        return Result.success(count);
    }

    /**
     * 描述： 根据案由编码及当事人查询1年内违法列表
     *
     * @author: zhengqiang
     * @date: 2022/6/24
     * @param: queryDto
     * @return {@link Result< CaseMainQueryByYearVo>}
     **/
    @PostMapping(value = "/getCaseMainListByReasonCodeAndParty")
    public Result<CaseMainQueryByYearVo> getCaseMainListByReasonCodeAndParty(@RequestBody CaseReasonQueryDto queryDto) {
        CaseMainQueryByYearVo caseMain = simpleCaseService.getCaseMainListByReasonCodeAndParty(queryDto);
        return Result.success(caseMain);
    }

    /**
     * 描述： 根据案由编码及当事人查询2年内，重复违法（立案通过即算），全部违法（立案通过即算），责令改正
     *
     * @author: mahan
     * @date: 2023/2/6
     * @param: queryDto
     * @return {@link Result< CaseMainQueryByYearVo>}
     **/
    @PostMapping(value = "/getIllegalTimesByReasonCodeAndParty")
    public Result<CasePartyIllegalTimesVo> getIllegalTimesByReasonCodeAndParty(@RequestBody CaseReasonQueryDto queryDto) {
        CasePartyIllegalTimesVo caseMain = simpleCaseService.getIllegalTimesByReasonCodeAndParty(queryDto);
        return Result.success(caseMain);
    }

    /**
     * 根据案由编码及当事人获取N年内重复违法次数（立案通过即算）
     *
     * @param: queryDto
     * @return {@link Result}
     **/
    @PostMapping(value = "/getIllegalTimesCountByReasonCodeAndParty")
    public Result<Integer> getIllegalTimesCountByReasonCodeAndParty(@RequestBody CaseReasonQueryDto queryDto) {
        int count = simpleCaseService.getIllegalTimesCountByReasonCodeAndParty(queryDto);
        return Result.success(count);
    }


    /**
     * 简易处罚完成
     *
     * @author: zhengqiang
     * @date: 2022/6/15
     * @param: simpleCaseSaveFinishDto
     * @return {@link Result}
     **/
    @PostMapping("/saveCaseFinish")
    public Result saveCaseFinish(@Validated @RequestBody SimpleCaseSaveFinishDto simpleCaseSaveFinishDto) {
        if (simpleCaseService.saveCaseFinish(simpleCaseSaveFinishDto)) {
            // 是否更新案件状态
            return Result.success("success");
        }
        return Result.error("fail");
    }

    /**
     * 描述： 简易处罚暂存功能(暂存与自动保存调用)
     *
     * @author: zhengqiang
     * @date: 2022/6/21
     * @param: saveDto
     * @return {@link Result}
     **/
    @RequestMapping ("/saveTemporary")
    public Result saveTemporary(@RequestBody SimpleCaseSaveDto saveDto) {
        int count = simpleCaseService.saveTemporary(saveDto);
        if (count > 0) {
            return Result.success("暂存成功");
        }
        return Result.error("暂存失败！");
    }

    /**
     * 描述： 获取有执法证协办人员列表
     *
     * @author: zhengqiang
     * @date: 2022/6/22
     * @return {@link Result}
     **/
    @PostMapping(value = "/getAssistHandleList")
    public Result<List<HandleAssistVo>> getAssistHandleList() {
        return simpleCaseService.getAssistHandleList();
        //return punishCaseFeignClient.getAssistHandleList();
    }

    /**
     * 描述： 通过身份证获取用户具体信息
     *
     * @author: zhengqiang
     * @date: 2022/6/22
     * @param: idCardObj
     * @return {@link Result}
     **/
    @RequestMapping("/getPersonInfoByIdCard")
    public Result getPersonInfoByIdCard(@RequestBody JSONObject idCardObj) {
        return simpleCaseService.getPersonInfoByIdCard(idCardObj);
        //return punishCaseFeignClient.getPersonInfoByIdCard(idCardObj);
    }
    /**
     * 根据统一信用代码获取企业信息
     * @author liyafeng
     * @date 2022/7/1
      * @param tyxydm
     * @return {@link Result}
     */
    @GetMapping("/getEntInfoByTyxydm")
    public Result getEntInfoByTyxydm(@RequestParam("tyxydm") String tyxydm) {
        if(StringUtils.isBlank(tyxydm)){
            return Result.error("获取失败,统一信用代码不能为空！");
        }
//        JSONObject jsonObject=simpleCaseService.getEntInfoByTyxydm(tyxydm);
//      return  Result.success("获取成功",jsonObject);
        return simpleCaseService.getEntInfoByTyxydmOfPc(tyxydm);
    }

    /**
     * 【V1.4.1】描述： 获取历史最近3个办案人员
     *
     * @author: zhengqiang
     * @date: 2022/8/27
     * @param: request
     * @return {@link Result< List< HandleAssistVo>>}
     **/
    @PostMapping(value = "/getHisAssistHandleList")
    public Result<List<HandleAssistVo>> getHisAssistHandleList(@RequestBody HisAssistHandleRequest request) {
        return simpleCaseService.getHisAssistHandleList(request);
    }

    /**
     * 【V1.4.1】描述： 根据名称搜索机构用户
     *
     * @author: zhengqiang
     * @date: 2022/8/27
     * @param: userName
     * @return {@link Result}
     **/
    @GetMapping(value = "/searchOrgUserListByName")
    public Result<List<HandleAssistVo>> searchOrgUserListByName(@RequestParam String userName) {
        return simpleCaseService.searchOrgUserListByName(userName);
    }
    /**
     * 【V1.9.0】描述：获取条线列表
     *
     * @param orgCode
     * @return {@link Result<Object> }
     * @author zhengqiang
     * @date 2022/11/28
     */
    @GetMapping("/getLineInfo")
    public Result<List<LineTerritoryInfoVo>> getLineInfo(@RequestParam String orgCode) {
        List<LineTerritoryInfoVo> lineInfoListByOrgCode = sysDepartParamService.getLineInfoListByOrgCode(orgCode);
        return Result.success("查询成功", lineInfoListByOrgCode);
    }


    /**
     * 【V1.7.2】描述：获取简易程序重复立案记录
     *
     * @return {@link Result }
     * @author shishengyao
     * @date 2022/11/21
     */
    @PostMapping(value = "/getSimpleCaseRepeatList")
    public Result<List<SimpleCaseRepeatInfoVo>> getSimpleCaseRepeatList(@RequestBody @Validated SimpleCaseRepeatQueryDto queryDto) {
        List<SimpleCaseRepeatInfoVo> simpleCaseRepeatList = simpleCaseService.getSimpleCaseRepeatList(queryDto);
        return Result.success("成功",simpleCaseRepeatList);
    }

    /**
     * 【V1.7.2】描述：撤销简易程序案件
     *
     * @return {@link Result }
     * @author shishengyao
     * @date 2022/11/21
     */
    @PostMapping(value = "/saveSimpleCaseRecall")
    public Result<String> saveSimpleCaseRecall(@RequestBody @Validated SimpleCaseRecallSaveDto saveDto) {
        if (simpleCaseService.saveSimpleCaseRecall(saveDto)){
            return Result.success("撤销成功");
        }
        return Result.error("撤销失败");
    }
    /**
     * 【V1.7.2】描述：简易程序案件执行完毕
     *
     * @return {@link Result }
     * @author shishengyao
     * @date 2022/11/21
     */
    @PostMapping(value = "/saveSimpleCaseExecuteFinish")
    public Result<String> saveSimpleCaseExecuteFinish(@RequestBody @Validated SimpleCaseExecuteFinishSaveDto saveDto) {
        if (simpleCaseService.saveSimpleCaseExecuteFinish(saveDto)){
            return Result.success("操作成功");
        }
        return Result.error("操作失败");
    }
    /**
     *根据部门编码与机构编码获取对应的统一信用代码是否配置
     * @author liyafeng
     * @date 2022/11/23
     * @return {@link Result< String>}
     */
    @GetMapping("/getIsConfigUnicode")
    public Result<String> getSysDepartParamByOrgCodeAndDeptCode() {
        UserDTO userDTO= UserUtil.getUserInfo();
        String isConfig=Constant.STRING_0;
        try {
            SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(userDTO.getOrgCode(),userDTO.getDeptCode());
            if(null!=sysDepartParam&&StringUtils.isNotBlank(sysDepartParam.getUnicode())){
                isConfig=Constant.STRING_1;
            }else if(null==sysDepartParam){
                isConfig=Constant.STRING_2;
            }
        }catch (Exception e){
            isConfig=Constant.STRING_2;
        }

        return Result.success("获取成功",isConfig);
    }

}
